package com.lgd.factoryattendance.Activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lgd.factoryattendance.Bean.CustomElectricReportBean;
import com.lgd.factoryattendance.Bean.ProjectManagement;
import com.lgd.factoryattendance.Bean.ProjectSpinner;
import com.lgd.factoryattendance.Bean.ProjectType;
import com.lgd.factoryattendance.Bean.WorkHourStatistics;
import com.lgd.factoryattendance.R;
import com.lgd.factoryattendance.Utils.TimeUtils;
import com.lgd.factoryattendance.Utils.ToastUtils;
import com.lgd.factoryattendance.adapter.MyAdapter;
import com.lgd.factoryattendance.httpService.API;
import com.lgd.factoryattendance.httpService.httpPort.IResponse;
import com.lgd.factoryattendance.httpService.httpPort.IStringResponse;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/*
* 打包工时 Activity
*/

public class PackActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "PackActivity";
    LinearLayout layout_back, layout_parent, layout_selection_time, layout_down_time, layout_end_time;
    TextView tv_name, tv_dept, tv_start_time, tv_end_time, tv_duration, tv_clock_type, tv_down_time;
    ImageView iv_refresh;
    Button bt_add_project, bt_submit;
    EditText et_suggest;
    Long work_hour_id, user_id, dept_id;
    String str_end_time = "" , str_actual_time, str_start_time, produce_date, ANDROID_ID, clock_type_str,str_dept;
    boolean normal_clock = true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pack);
        initView();
        initData();
    }
    public void initView (){
        iv_refresh = findViewById(R.id.iv_refresh);
        iv_refresh.setOnClickListener(this);
        layout_back = findViewById(R.id.layout_back);
        layout_back.setOnClickListener(this);
        layout_selection_time = findViewById(R.id.layout_selection_time);
        layout_down_time = findViewById(R.id.layout_down_time);
        layout_down_time.setOnClickListener(this);
        layout_end_time = findViewById(R.id.layout_end_time);
        tv_down_time = findViewById(R.id.tv_down_time);
        tv_name = findViewById(R.id.tv_name);
        tv_dept = findViewById(R.id.tv_dept);
        tv_start_time = findViewById(R.id.tv_start_time);
        tv_end_time = findViewById(R.id.tv_end_time);
        tv_duration = findViewById(R.id.tv_duration);
        tv_clock_type = findViewById(R.id.tv_clock_type);
        layout_parent = findViewById(R.id.layout_parent);
        bt_add_project = findViewById(R.id.bt_add_project);
        bt_add_project.setOnClickListener(this);
        et_suggest = findViewById(R.id.et_suggest);
        bt_submit = findViewById(R.id.bt_submit);
        bt_submit.setOnClickListener(this);
    }
    public void initData (){
        ANDROID_ID = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
        Intent intent = getIntent();
        work_hour_id = intent.getLongExtra("workhourid",0);
        str_end_time = intent.getStringExtra("endTime");
        System.out.println("----下班时间----"+str_end_time);
        if (TextUtils.isEmpty(str_end_time)){
            layout_end_time.setVisibility(View.GONE);
            layout_selection_time.setVisibility(View.VISIBLE);
            normal_clock = false;   // 异常 打卡
        }else {
            layout_end_time.setVisibility(View.VISIBLE);
            layout_selection_time.setVisibility(View.GONE);
            normal_clock = true;
        }
        WorkHourStatistics w = new WorkHourStatistics();
        w.setWorkhourid(work_hour_id);
        findWorkHour(w);

        projectType(); // 项目类型
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.bt_add_project:
                project_number++;
                String duration = tv_duration.getText().toString();
                if (duration.isEmpty()){
                    ToastUtils.warnShowLong(getApplicationContext(),"请选择时间");
                }else {
                    Double d = div(Double.parseDouble(duration), project_number,2);
                    String s = String.valueOf(d);
                    addProjectSublayout ();
                    for (int j = 0; j < textViewList.size(); j++) {
                        TextView textViewToUpdate = textViewList.get(j);
                        textViewToUpdate.setText(s);
                    }
                }
                break;
            case R.id.bt_submit:
                String str_duration = tv_duration.getText().toString();
                if (str_duration.isEmpty()){
                    ToastUtils.warnShowLong(getApplicationContext(),"确保时长不为空！！！");
                }else {
                    if (getValue()){
                        setReport();
                    }else {
                        ToastUtils.warnShowLong(PackActivity.this,"确保数据不为空！");
                    }
                }
                break;
            case R.id.layout_down_time:  // 选择 下班时间
                String start_time = tv_start_time.getText().toString();
                TimeUtils.timeSelect(PackActivity.this, start_time , new TimeUtils.TimePickerCallback() {
                    @Override
                    public void onTimePicked(Boolean b, String formattedDateTime) {
                        System.out.println("---选择后时间：---"+formattedDateTime+"---时间比较---"+ b);
                        if (b){      //  true  选择时间 < 开始时间
                            tv_down_time.setText("");
                        }else {
                            tv_down_time.setText(formattedDateTime);
                            CalculationTime(tv_start_time.getText().toString(),user_id);
                        }
                    }
                });
                break;
            case R.id.layout_back:
                finish();
                break;
            case R.id.iv_refresh:
                reStartActivity();
                break;
            default:
                break;
        }
    }
    int project_number ;
    private ArrayList<TextView> textViewList = new ArrayList<>();
    private ArrayList<TextView> projectTVList = new ArrayList<>();
//  自定义 动态添加布局
    public void addProjectSublayout (){
        // 创建新的LinearLayout实例
        LinearLayout newLinearLayout = new LinearLayout(this);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        newLinearLayout.setOrientation(LinearLayout.VERTICAL);
        newLinearLayout.setBackgroundResource(R.drawable.rounded_background);
        layoutParams.setMargins(dpToPx(30),dpToPx(20),dpToPx(30),0);
        newLinearLayout.setLayoutParams(layoutParams);

        // 创建 标题  titleLinearLayout
        LinearLayout title_layout = new LinearLayout(this);
        LinearLayout.LayoutParams titleLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        titleLayoutParams.setMargins(0,dpToPx(10),0,0);
        title_layout.setLayoutParams(titleLayoutParams);
        //  项目
        TextView title_tv = new TextView(this);
        LinearLayout.LayoutParams titleParams = new LinearLayout.LayoutParams( 0, 50, 7);
        title_tv.setLayoutParams(titleParams);
        title_tv.setText("项目 "+project_number);
        title_tv.setTextSize(20);
        title_tv.setGravity(Gravity.LEFT);
        titleParams.setMargins(dpToPx(15),0,0,0);
        title_layout.addView(title_tv);
        projectTVList.add(title_tv);

        // 创建并添加Button到newLinearLayout
        Button bt_delect = new Button(this);
        LinearLayout.LayoutParams de_button_params = new LinearLayout.LayoutParams(
                0, 40,1);
        bt_delect.setLayoutParams(de_button_params);
        bt_delect.setText("删  除");
        bt_delect.setGravity(Gravity.CENTER);
        bt_delect.setBackgroundResource(R.drawable.delect_button);
        de_button_params.setMargins(0,0,dpToPx(5),0);
        bt_delect.setTextColor(Color.parseColor("#ffffff"));
        bt_delect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                project_number--;
                layout_parent.removeView(newLinearLayout);
                String duration = tv_duration.getText().toString();
                if (project_number > 0){
                    double d = div(Double.valueOf(duration), project_number,2);  // 被除数不为 0
                    String s = String.valueOf(d);
                    for (int j = 0; j < textViewList.size(); j++) {
                        TextView textViewToUpdate = textViewList.get(j);
                        textViewToUpdate.setText(s);
                    }
                    for (int z = 0; z < projectTVList.size(); z++) {
                        TextView projectTextViewToUpdate = projectTVList.get(z);
                        projectTextViewToUpdate.setText("项目 "+project_number);
                    }
                }
            }
        });
        title_layout.addView(bt_delect);

        // 项目 类型 project_type_layout
        LinearLayout project_type_layout = new LinearLayout(this);
        project_type_layout.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));

        //  项目类型 tv_project_type
        TextView tv_project_type = new TextView(this);
        LinearLayout.LayoutParams tv_project_type_params = new LinearLayout.LayoutParams(
                0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f);
        tv_project_type_params.setMargins(0,dpToPx(10),0,0);
        tv_project_type.setLayoutParams(tv_project_type_params);

        tv_project_type.setLayoutParams(tv_project_type_params);
        tv_project_type.setText("选择项目类型:");
        tv_project_type.setTextSize(20);
        tv_project_type.setGravity(Gravity.CENTER);
        project_type_layout.addView(tv_project_type);

        // 项目类型 下拉框 sp_project_type
        Spinner sp_project_type = new Spinner(this);
        LinearLayout.LayoutParams sp_project_type_params = new LinearLayout.LayoutParams(
                0, LinearLayout.LayoutParams.WRAP_CONTENT, 3f);
        sp_project_type.setLayoutParams(sp_project_type_params);

        Drawable background_type = ContextCompat.getDrawable(this, R.drawable.assembly_info_background);
        if (background_type != null){ sp_project_type.setBackground(background_type); }
        project_type_layout.addView(sp_project_type);

        //  项目 名称   project_name_layout
        LinearLayout project_name_layout = new LinearLayout(this);
        LinearLayout.LayoutParams project_name_params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT
        );
        project_name_params.setMargins(0,dpToPx(10),0,0);
        project_name_layout.setLayoutParams(project_name_params);

        // 项目名称 tv_project_name
        TextView tv_project_name = new TextView(this);
        LinearLayout.LayoutParams tv_project_name_params = new LinearLayout.LayoutParams(
                0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f);
        tv_project_name_params.setMargins(0,dpToPx(10),0,0);
        tv_project_name.setLayoutParams(tv_project_name_params);

        tv_project_name.setLayoutParams(tv_project_name_params);
        tv_project_name.setText("请选择项目:");
        tv_project_name.setTextSize(20);
        tv_project_name.setGravity(Gravity.CENTER);
        project_name_layout.addView(tv_project_name);

        // 项目名称spinner   sp_project_name
        Spinner sp_project_name = new Spinner(this);

        typeSpinner(sp_project_type,sp_project_name);


        LinearLayout.LayoutParams sp_project_name_params = new LinearLayout.LayoutParams(
                0, LinearLayout.LayoutParams.WRAP_CONTENT, 3f);
        sp_project_name.setLayoutParams(sp_project_name_params);
        Drawable background = ContextCompat.getDrawable(this, R.drawable.assembly_info_background);
        if (background != null){
            sp_project_name.setBackground(background);
        }
        project_name_layout.addView(sp_project_name);

        // 创建 时长 duration_layout
        LinearLayout duration_layout = new LinearLayout(this);
        LinearLayout.LayoutParams duration_params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        duration_layout.setLayoutParams(duration_params);

        TextView tv_duration_title= new TextView(this);
        LinearLayout.LayoutParams tv_duration_params = new LinearLayout.LayoutParams(
                0, 50, 1f);
        tv_duration_title.setLayoutParams(tv_duration_params);
        tv_duration_title.setText("工作时长:");
        tv_duration_title.setTextSize(20);
        tv_duration_title.setGravity(Gravity.CENTER);
        duration_layout.addView(tv_duration_title);

        TextView duration_tv = new TextView(this);
        LinearLayout.LayoutParams durationParams = new LinearLayout.LayoutParams( 0, 50 , 3);
        duration_tv.setLayoutParams(durationParams);
        duration_tv.setText("");
        duration_tv.setTextSize(23);
        duration_tv.setTextColor(Color.parseColor("#4169E1"));
        duration_tv.setGravity(Gravity.CENTER);
        duration_layout.addView(duration_tv);
        textViewList.add(duration_tv);

        // 详情 details_layout
        LinearLayout details_layout = new LinearLayout(this);
        details_layout.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        details_layout.setOrientation(LinearLayout.HORIZONTAL);

        TextView text_et = new TextView(this);
        LinearLayout.LayoutParams textETParams = new LinearLayout.LayoutParams(
                0, 50, 1f);
        text_et.setLayoutParams(textETParams);
        text_et.setText("详情描述:");
        text_et.setTextSize(20);
        text_et.setGravity(Gravity.CENTER);
        details_layout.addView(text_et);

        //  问题 输入框
        EditText editText = new EditText(this);
        LinearLayout.LayoutParams editTextParams = new LinearLayout.LayoutParams(
                0, LinearLayout.LayoutParams.WRAP_CONTENT, 3f);
        editText.setLayoutParams(editTextParams);
        editText.setBackgroundResource(R.drawable.edittext_border);
        editText.setMinHeight(85);
        editText.setGravity(Gravity.CENTER);
        editTextParams.setMargins(0,dpToPx(10),dpToPx(15),dpToPx(15));
        details_layout.addView(editText);

        newLinearLayout.addView(title_layout);
        newLinearLayout.addView(project_type_layout);
        newLinearLayout.addView(project_name_layout);
        newLinearLayout.addView(duration_layout);
        newLinearLayout.addView(details_layout);

        layout_parent.addView(newLinearLayout);  // 添加到父布局中  layout_parent
    }
    private ArrayList<CustomElectricReportBean> packReportList = null;
    //  获取  动态布局
    boolean isOK ;
    public boolean getValue(){
        isOK = false;
        packReportList = new ArrayList<>();
        ViewGroup layout_parent = findViewById(R.id.layout_parent);
        if (layout_parent.getChildCount() == 0){
            ToastUtils.warnShowLong(getApplicationContext(),"至少添加一项项目!!!");
        }else {
            for (int i = 0; i < layout_parent.getChildCount(); i++) {
                LinearLayout linearLayout = (LinearLayout) layout_parent.getChildAt(i);
                LinearLayout project_type_layout = (LinearLayout) linearLayout.getChildAt(1);
                LinearLayout project_name_layout = (LinearLayout) linearLayout.getChildAt(2);
                LinearLayout duration_layout = (LinearLayout) linearLayout.getChildAt(3);
                LinearLayout details_layout = (LinearLayout) linearLayout.getChildAt(4);

                Spinner sp_type = (Spinner) project_type_layout.getChildAt(1);
                Spinner sp_projectName = (Spinner) project_name_layout.getChildAt(1);
                TextView tv_duration = (TextView) duration_layout.getChildAt(1);
                EditText et_describe = (EditText) details_layout.getChildAt(1);

                String str_type = sp_type.getSelectedItem().toString();
                String str_duration = tv_duration.getText().toString();
                String str_describe = et_describe.getText().toString();

                if (str_type.equals("选择类型")){
                    isOK = false;
                }else if (str_describe.equals("")){
                    isOK = false;
                }else {
                    isOK = true;
                    Object str_projectName = sp_projectName.getSelectedItem();
                    Long projectCodeid = ((ProjectSpinner)str_projectName).getProjectId();
                    String str_projectName2 = ((ProjectSpinner)str_projectName).getProjectName();

                    System.out.println("项目"+str_projectName2+
                            "----项目id：---"+ projectCodeid +
                            "**** 时长：****"+str_duration+
                            "~~~~ 描述：~~~~~"+str_describe);

                    packReportList.add(new CustomElectricReportBean(projectCodeid, str_duration, str_describe ));

                }
            }
        }
        return isOK;
    }

    public void setReport(){
        String str_suggest = et_suggest.getText().toString();
        if (packReportList.size() > 0){
            for (int j = 0; j < packReportList.size(); j++) {
                WorkHourStatistics w = new WorkHourStatistics();
                // 相同
                w.setProjectId(packReportList.get(j).getId());
                w.setDuration(packReportList.get(j).getEl_duration());
                w.setWorkDetails(packReportList.get(j).getEl_describe());
                w.setBelowSerialNo(ANDROID_ID);
                if (j == 0) {           //   修改 工单
                    if (normal_clock) {
                        w.setEndtime(tv_end_time.getText().toString());
                    } else {
                        w.setEndtime(tv_down_time.getText().toString());
                    }
                    w.setRationalizationProposal(str_suggest);
                    w.setWorkhourid(work_hour_id);

                    updateWorkHourStatistics(w);
                } else {
                    w.setDeptId(dept_id);
                    w.setUserid(user_id);
                    w.setProducedate(produce_date);
                    w.setStarttime(tv_start_time.getText().toString());
                    if (normal_clock) {
                        w.setEndtime(tv_end_time.getText().toString());
                    } else {
                        w.setEndtime(tv_down_time.getText().toString());
                    }
                    w.setClocktype(clock_type_str);
                    w.setUpperSerialNo(ANDROID_ID);
                    w.setStatus("已下班");

                    workClockIn(w);
                }
            }
        }
    }
    // 修改 信息
    public void updateWorkHourStatistics(WorkHourStatistics w){
        API.updateWorkHourStatistics(w, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                PackActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(result);
                        String msg = j.getString("msg");
                        switch (msg){
                            case "操作成功":
                                ToastUtils.successShowLong(getApplicationContext(),"日报上报成功！");
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        //  返回首页
                                        Intent intent = new Intent(PackActivity.this,HomePageActivity.class);
//                                        setResult(Activity.RESULT_OK,intent);
                                        startActivity(intent);
                                        finish();
                                    }
                                },300);
                                break;
                            case "已下班":
                                ToastUtils.warnShowLong(getApplicationContext(),"该工单已打下班卡，无法重复修改");
                                break;
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }
    public void workClockIn(WorkHourStatistics w){
        API.addWorkClockIn( w, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                PackActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(result);
                        String code = j.getString("code");
                        if (code.equals("200")){
                            ToastUtils.successShowLong(getApplicationContext(),"上报成功!!!");
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }

    // 根据 workid 。。。。
    public void findWorkHour(WorkHourStatistics workHourStatistics){
        API.clockInStatus(workHourStatistics, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                PackActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject jsonObject = JSONObject.parseObject(result);
                        List<WorkHourStatistics> workHourList = new Gson().fromJson(jsonObject.getString("data"), new TypeToken<List<WorkHourStatistics>>(){}.getType());
                        System.out.println("====gongdan 信息======"+workHourList);
                        if (workHourList != null && workHourList.size() > 0){
                            str_start_time = workHourList.get(0).getStarttime();
                            str_dept = workHourList.get(0).getDeptName();

                            tv_name.setText(workHourList.get(0).getNickName());
                            tv_dept.setText(workHourList.get(0).getDeptName());
                            tv_start_time.setText(str_start_time);
                            tv_end_time.setText(str_end_time);
                            tv_clock_type.setText(workHourList.get(0).getClocktype());
                            clock_type_str = workHourList.get(0).getClocktype();

                            user_id = workHourList.get(0).getUserid();
                            dept_id = workHourList.get(0).getDeptId();
                            produce_date = workHourList.get(0).getProducedate();

                            CalculationTime(str_start_time, user_id);   // 计算时长
                        }
                    }
                });

            }
            @Override
            public void onFail(int statusCode) {}
        });
    }
    // 计算工时
    public void CalculationTime (String str_start, Long user_id){
        if (normal_clock){
            WorkHourStatistics w = new WorkHourStatistics();
            w.setStarttime(str_start);
            w.setUserid(user_id);
            w.setEndtime(str_end_time);
            calculateDuration(w);
        }else {
            String str_select_down_time = tv_down_time.getText().toString();
            WorkHourStatistics w = new WorkHourStatistics();
            w.setStarttime(str_start);
            w.setUserid(user_id);
            w.setEndtime(tv_down_time.getText().toString());
            if (TimeUtils.isDateTimeValid(str_select_down_time)){   // 判断是否为正确的时间格式
                calculateDuration(w);
            }else {
                ToastUtils.warnShowLong(getApplicationContext(),"请选择正确的日期格式");
            }
        }
    }
    //  根据 开始 + 结束 + useid 查询工时
    public void calculateDuration(WorkHourStatistics w){
        API.calculateDuration(w, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                PackActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject jsonObject = JSONObject.parseObject(result);
                        str_actual_time = jsonObject.getString("msg");
                        System.out.println("----工时-----"+ str_actual_time);
                        tv_duration.setText(str_actual_time);
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }
    // 获取 项目分类 数据
    public List<String> projectType_list = new ArrayList<>();
    public void projectType(){
        API.projectType(new IResponse() {
            @Override
            public void onSuccess(String response) throws IOException {
                PackActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(response);
                        List<ProjectType> projectTypeList = new Gson().fromJson(j.getString("data"), new TypeToken<List<ProjectType>>(){}.getType());
                        Log.d(TAG, "-----项目类型----"+projectTypeList);
                        if (projectTypeList.size() > 0){
                            projectType_list.add("选择类型");
                            for (ProjectType type : projectTypeList) {
                                projectType_list.add(type.getTypename());
                            }
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {
                Log.d(TAG, "onFail: -----刷新错误------:  "+statusCode);
            }
        });
    }
    ArrayAdapter<String> typeSpinner_adapter;
    //  类型 spinner 实例化
    public void typeSpinner (Spinner sp_project_type ,Spinner sp_project_name){
        typeSpinner_adapter = new ArrayAdapter<>(getApplicationContext(),R.layout.spinner_item,projectType_list);
        sp_project_type.setAdapter(typeSpinner_adapter);
        sp_project_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Log.d(TAG, "----spinner选中类型----"+projectType_list.get(position));
                String str_spinner = projectType_list.get(position);
                if (str_spinner.equals("选择类型")) {
                    ToastUtils.warnShowLong(getApplicationContext(),"请选择项目类型！！！");
                }else {
                    ProjectType projectType = new ProjectType();
                    projectType.setTypename(projectType_list.get(position));
                    projectType.setSerialnumber(ANDROID_ID);
                    getStartProjectInfo(projectType, sp_project_name);
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
    }
    private  List<ProjectSpinner> projectnameList = null;  // 项目 列表
    public void getStartProjectInfo(ProjectType projectType, Spinner spinner){
        API.getStartProjectInfo(projectType, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                PackActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(result);
                        List<ProjectManagement> projectManagementList = new Gson().fromJson(j.getString("data"), new TypeToken<List<ProjectManagement>>(){}.getType());
                        System.out.println("----项目列表------"+projectManagementList);
                        projectnameList = new ArrayList<>();
                        if (projectManagementList.size() > 0){
                            for (ProjectManagement p : projectManagementList) {
                                projectnameList.add(new ProjectSpinner(p.getProjectname(),
                                        p.getProductacode(),
                                        p.getProjectid(),
                                        p.getDeptid()));
                            }
                        }else {
                            ToastUtils.warnShowLong(getApplicationContext(),"本设备下没有对应项目类型的项目，请重新选择!");
                        }

                        Log.d(TAG, "run: ----projectnameList2-----"+projectnameList);
                        setProject(projectnameList, spinner);
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }

    public void setProject(List<ProjectSpinner> projectnameList ,Spinner spinner){
        MyAdapter adapter = new MyAdapter(projectnameList, PackActivity.this);
        spinner.setAdapter(adapter);
    }
    private void reStartActivity() {   // 刷新 当前Activity
        Intent intent = getIntent();
        overridePendingTransition(0, 0);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        finish();
        overridePendingTransition(0, 0);
        startActivity(intent);
    }
    // 点击键盘外 关闭软键盘
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }
    public  boolean isShouldHideInput(View v, MotionEvent event) {
        if ((v instanceof EditText)) {
            int[] leftTop = { 0, 0 };
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }
    //    dp  转化为  像素
    public int dpToPx(int dp) {
        float density = getResources().getDisplayMetrics().density;
        return Math.round((float) dp * density);
    }
    // 两数 相除 精度
    public double div(double a,int b,int scale){
        BigDecimal b1 = new BigDecimal(Double.toString(a));
        BigDecimal b2 = new BigDecimal(Double.toString(b));
        return b1.divide(b2, scale,BigDecimal.ROUND_HALF_UP).doubleValue();
    }
}